package com.ddm.job;

import com.ddm.mapper.UserSubscribeMapper;
import com.ddm.service.webService.UserSubscribeService;
import com.ddm.vo.webVo.SubscribeDetailVO;
import lombok.RequiredArgsConstructor;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;

@Component
@RequiredArgsConstructor
public class ExpiringSubscribeJob implements Job {

    // 注入查询服务
    private final UserSubscribeService userSubscribeService;

    // 注入用于存储的Mapper
    private final UserSubscribeMapper userSubscribeMapper;

    // 提前预警的天数（建议配置在application.yml中）
    private static final Integer WARNING_DAYS = 15;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try {
            // 1. 查询即将到期的订阅
            List<SubscribeDetailVO> expiringList = userSubscribeService.getExpiringSubscribes(WARNING_DAYS);
            if (expiringList.isEmpty()) {
                System.out.println("没有即将到期的订阅记录，无需存储");
                return;
            }
            // 2. 补充存储所需的额外字段（如果需要）
//            expiringList.forEach(vo -> {
//                // 例如：如果需要记录存储时间，可添加字段并设置
//                // vo.setStoreTime(LocalDateTime.now());
//            });

            // 3. 批量存入数据库（使用已有的Mapper或新增方法）
            // 注意：需要在SubscribeMapper中新增batchInsertExpiring方法
            int rows = userSubscribeMapper.batchInsertExpiring(expiringList);
            System.out.println("Quartz任务执行成功，存入 " + rows + " 条即将到期订阅记录");

        } catch (Exception e) {
            // 任务执行失败处理
            throw new JobExecutionException("处理即将到期订阅失败", e, false);
        }
    }
}
